package org.jeecg.modules.coze_workflow.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.coze.workflow.dto.CozeWorkflowRunDTO;
import org.jeecg.modules.coze.workflow.service.ICozeWorkflowService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: Coze工作流服务实现类
 * @Author: jeecg-boot
 * @Date: 2025-06-28
 * @Version: V1.0
 */
@Service
@Slf4j
public class CozeWorkflowServiceImpl implements ICozeWorkflowService {

    @Value("${coze.api.token}")
    private String apiToken;

    @Value("${coze.api.base-url}")
    private String baseUrl;

    @Override
    public Result<JSONObject> runWorkflow(CozeWorkflowRunDTO dto) {
        try {
            System.out.println("开始执行Coze工作流，workflowId: " + dto.getWorkflowId() + ", input: " + dto.getInput());
            
            // 构造请求参数 - 根据Coze API文档调整参数结构
            JSONObject params = new JSONObject();
            params.put("workflow_id", dto.getWorkflowId());
            params.put("is_async", false); // 同步执行
            
            JSONObject parameters = new JSONObject();
            parameters.put("input", dto.getInput());
            params.put("parameters", parameters);
            
            System.out.println("构造的请求参数: " + params.toJSONString());

            // 发送请求到Coze API，最多重试5次
            JSONObject response = callCozeAPIWithRetry("/v1/workflows/run", params, 5);

            if (response != null) {
                System.out.println("Coze API返回结果: " + response.toJSONString());
                return Result.OK(response);
            } else {
                System.out.println("执行失败：响应数据为空");
                return Result.error("执行失败：响应数据为空");
            }
        } catch (Exception e) {
            System.out.println("运行Coze工作流异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("运行异常：" + e.getMessage());
        }
    }

    /**
     * 调用Coze API，带重试机制
     *
     * @param endpoint API端点
     * @param params 请求参数
     * @param maxRetries 最大重试次数
     * @return
     */
    private JSONObject callCozeAPIWithRetry(String endpoint, JSONObject params, int maxRetries) {
        int attempt = 0;
        while (attempt < maxRetries) {
            try {
                attempt++;
                System.out.println("第 " + attempt + " 次尝试调用Coze API");
                return callCozeAPI(endpoint, params);
            } catch (HttpServerErrorException e) {
                System.out.println("第 " + attempt + " 次调用Coze API失败: " + e.getMessage());
                // 如果是500错误且不是最后一次尝试，则等待一段时间后重试
                if (attempt < maxRetries && (e.getStatusCode().value() == 500 || e.getStatusCode().value() == 5000)) {
                    try {
                        // 等待时间逐渐增加：1秒、2秒、4秒、8秒...
                        long waitTime = (long) Math.pow(2, attempt - 1) * 1000;
                        System.out.println("等待 " + waitTime + " 毫秒后重试...");
                        Thread.sleep(waitTime);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                } else {
                    throw e;
                }
            }
        }
        return null;
    }

    /**
     * 调用Coze API
     *
     * @param endpoint API端点
     * @param params 请求参数
     * @return
     */
    private JSONObject callCozeAPI(String endpoint, JSONObject params) {
        try {
            System.out.println("准备调用Coze API，endpoint: " + endpoint + ", baseUrl: " + baseUrl);
            
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiToken);
            
            System.out.println("请求Header信息，Authorization: Bearer " + 
                (apiToken != null ? apiToken.substring(0, Math.min(apiToken.length(), 10)) + "..." : "null"));

            // 创建请求实体
            HttpEntity<String> entity = new HttpEntity<>(params.toJSONString(), headers);
            
            System.out.println("发送请求到: " + baseUrl + endpoint);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    baseUrl + endpoint, entity, String.class);

            System.out.println("收到HTTP响应，状态码: " + response.getStatusCode() + "，响应体长度: " + 
                (response.getBody() != null ? response.getBody().length() : 0));
            
            if (response.getBody() != null) {
                System.out.println("响应内容前200字符: " + 
                    response.getBody().substring(0, Math.min(200, response.getBody().length())));
            }

            // 解析响应
            if (response.getBody() != null && !response.getBody().isEmpty()) {
                return JSONObject.parseObject(response.getBody());
            } else {
                System.out.println("响应体为空或null");
                return null;
            }
        } catch (Exception e) {
            System.out.println("调用Coze API异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}